package com.zlz.open.ugs.exchange.response;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @Author: zhulinzhong
 * @Date: 2024/5/25
 */
public class UgsResponse {

    private final ServerHttpResponse response;

    private byte[] body;

    private final MultiValueMap<String, String> headers;

    public UgsResponse(ServerHttpResponse response) {
        this.response = response;
        this.headers = new HttpHeaders();
    }

    public Mono<Void> write(HttpStatus httpStatus) {
        response.setStatusCode(httpStatus);

        // 请求头
        response.getHeaders().addAll(headers);
        body = body == null ? new byte[0] : body;
        return response.writeWith(Flux.just(response.bufferFactory().wrap(body)));
    }

    public Mono<Void> write() {
        return write(HttpStatus.OK);
    }

    public Mono<Void> write(byte[] body, HttpStatus httpStatus) {
        this.body = body;
        return write(httpStatus);
    }

    public Mono<Void> write(byte[] body) {
        this.body = body;
        return write();
    }


    public static class Builder {
        private ServerHttpResponse response;

        public Builder response(ServerHttpResponse response) {
            this.response = response;
            return this;
        }

        public UgsResponse build() {
            return new UgsResponse(response);
        }
    }
}
